<?php
// application/controllers/RelationController.php

/**
 * RelationController is the controller for handling relations
 *

 * @author Hermen van den Hoorn
 * @version $Id$
 */
class RelationController extends Vakanz_CRM_Controller_Adminaction
{
    /**
     * The "index" action is the default action for all controllers.
     *
     * Assuming the default route and default router, this action is dispatched
     * via the following urls:
     *   /relation/
     *   /realation/index
     *
     * @return void
     */
	public function cancelfiltersAction() {
		$filter = new Zend_Session_Namespace('relation_filter');
		$filter->unsetAll();
		$this->_forward('index');
		
	}
	
	public function indexAction() {
		$relations =new Vakanz_Relations();
		$select = $relations->select();
		$filter = new Zend_Session_Namespace('relation_filter');
		
		if ($this->_getParam('sort')){
			$filter->sort = $this->_getParam('sort');
		}
		if ($this->_getParam('keyword') != '' && $this->_getParam('context') != '') {
			$filter->keyword = $this->_getParam('keyword');
			$filter->context = $this->_getParam('context');
		}
		if ($this->_getParam('attribute') != '' || $this->getRequest()->getMethod() == 'POST' ) {
			$filter->paramAttributes = $this->_getParam('attribute');
		}
		
		if (!empty($filter->sort)) {
			if ($filter->sort =='address') {
				$select->order('relation_street');
				$select->order('relation_housenumber');
			} else {
				$select->order('relation_'.$filter->sort);
			}
		}
		if ($filter->keyword != '' && $filter->context != '') {
//			var_dump($filter->context);
//			exit;
			$context = $filter->context;
			$contextItem = array_shift($context);
			if (!empty($contextItem)) {
				$extraWhere = '(';
				$extraWhere .= '`relation_'.$contextItem.'` LIKE "%'.$filter->keyword.'%"';
				foreach ($context as $contextItem) {
					$extraWhere .= ' or `relation_'.$contextItem.'` LIKE "%'.$filter->keyword.'%"';
				}
				$extraWhere .= ')';
				$select->where($extraWhere);
			}
		}
		if (!empty($filter->paramAttributes)) {
			$relationAttributes = new Vakanz_Relation_Attributes();
			$select->from(array('r' => $relations->info('name')), '*');
			$teller = 1;
			foreach($filter->paramAttributes as $paramAttribute) {
				$select->join(array('ra'.$teller=>$relationAttributes->info('name')), ' r.`relation_id` =ra'.$teller.'.`relation_id`',null);
				$select->where('ra'.$teller.'.attribute_id = '.$paramAttribute);
				$teller++;
			}
			$select->group('r.relation_id');
		}
		$select->order('relation_valid_from DESC');
		$relationsRs = $relations->fetchAll($select);
		
		$relationObjArray = array();
		foreach ($relationsRs as $relation) {
			$relationMeta = $relation->getRelationMeta();
			$relationYears = $relation->getRelationYears();
			
			$relationObj = $relation->toStdObject();
			if ($relationMeta) {
				$relationObj->relation_meta = $relationMeta->toStdObject();
			}
			if ($relationYears) {
				$relationObj->relation_years = $relationYears->toStdObjectArray();
			}
			$relationObjArray[] = $relationObj;
		}
		
		$this->view->relations = $relationObjArray;
		$this->_helper->actionStack('filteroptions');
	}

	public function lasteditedAction() {
		$relations =new Vakanz_Relations();
		$relationsRs = $relations->fetchAll($relations->select()->order('relation_valid_from DESC')->limit(10));
		$this->view->relations = $relationsRs->toStdObjectArray();
	}
    public function newAction()
    {
        $this->_forward('edit');
    }
    public function editAction() {
    	$relations = new Vakanz_Relations();
    	if ($this->_getParam('relation_id')) {
    		$this->view->relation = $relations->getRelation($this->_getParam('relation_id'));
    	} else {
    		$this->view->relation = $relations->createRow();
    	}
    	$relation = $relations->createRow();
		$forms = new General_Forms();
		$form = $forms->findByName('relation');
		$form->getFormElements();
		$formObj = $form->toStdObject();
        $this->view->form = $formObj;

        $this->_helper->actionStack('search');

    }
    
    public function editmetaAction() {
    	$relationmetaObj = new stdClass();
    	$relationmetaObj->sortrelation = '';
    	$relationmetaObj->refo = '';
    	$relationmetaObj->sortrequest = '';
    	$relationmetaObj->years = array();
    	
    	$relations = new Vakanz_Relations();
    	if ($this->_getParam('relation_id')) {
    		$relation = $relations->getRelation($this->_getParam('relation_id'));
    		if ($relation) {
    			$relationmeta = $relation->getRelationMeta();
    			$relationyears = $relation->getRelationYears();
    			if ($relationmeta) {
    				$relationmetaObj->sortrelation = $relationmeta->relationmeta_sortrelation;
    				$relationmetaObj->sortrequest = $relationmeta->relationmeta_sortrequest;
    				$relationmetaObj->refo = $relationmeta->relationmeta_refo;
    			}
    			if ($relationyears) {
    				foreach($relationyears as $relationYear) {
    					$relationmetaObj->years[] = $relationYear->year;
    				}
    			}
    		}
    	}
    	$this->view->relationmeta = $relationmetaObj;
    }
    
    public function searchAction() {
    	$this->render($this->getRequest()->getActionName(),'right');
    }
	public function filteroptionsAction() {
		$filter = new Zend_Session_Namespace('relation_filter');
		$attributes = new Vakanz_Attributes();
		$this->view->attributes = $attributes->fetchAll();
    	$this->view->contextParams = $filter->context;
    	$this->view->attributeParams = $filter->paramAttributes;
    	$this->view->keyword = $filter->keyword;

    	$this->render($this->getRequest()->getActionName(),'right');

	}
	
	public function deleteAction() {
    	$relations = new Vakanz_Relations();
    	if ($this->_getParam('relation_id') == 0) {
    		$this->view->message = 'Relatie bestaat niet.';
    	} else {
    		$relation = $relations->getRelation($this->_getParam('relation_id'));
    		$relation->delete();
    		$this->view->message = 'Relatie verwijdert.';
    	}
    	$this->_forward('index');
	}
	
    public function checkAction() {
    	$relations = new Vakanz_Relations();
    	if ($this->_getParam('relation_id') == 0) {
    		$relation = $relations->createRow();
    	} else {
    		$relation = $relations->getRelation($this->_getParam('relation_id'));
    	}
    	$relation->fillByParams($this->_request->getParams());
    	if ($this->_getParam('relation_id') == 0) {
	    	if ($relation->isExisting()) {
	    		$existing = $relation->getExistingRelation();
	    		$this->view->relation = $relation;
	    		$this->view->existing_relation = $relation;
	    	} else {
	    		$this->_forward('save');
	    	}
    	} else {
    		$this->_forward('save');
    	}

    }

    public function saveAction() {
    	$relations = new Vakanz_Relations();
    	if ($this->_getParam('relation_id') == 0) {
    		$relation = $relations->createRow();
    	} else {
    		$relation = $relations->getRelation($this->_getParam('relation_id'));
    	}
    	$relation->fillByParams($this->_request->getParams());
    	$attr = new Vakanz_Relation_Attribute();
    	$relation->save();
    	$this->saveAttributes($relation);
    	$this->saveRelationMeta($relation);
    	$this->saveRelationYears($relation);
    }
    
    private function saveRelationMeta(Vakanz_Relation $relation) {
    	$relationMeta = $relation->getRelationMeta();
    	if (!$relationMeta) {
    		$relationMetas = new Vakanz_Relation_Metas();
    		$relationMeta = $relationMetas->createRow(array('relation_id'=> $relation->relation_id));
    	}
    	$relationMeta->relationmeta_refo = $this->_getParam('refo');
    	$relationMeta->relationmeta_sortrelation = $this->_getParam('sort');
   		$relationMeta->relationmeta_sortrequest = $this->_getParam('sort_request');
    	$relationMeta->save();
    }
    
    private function saveRelationYears(Vakanz_Relation $relation) {
    	$relationYearRs = $relation->getRelationYears();
    	if ($this->_getParam('years') != '') {
    		$years = $this->_getParam('years');
    	} else {
    		$years = array();
    	}
    	foreach ($relationYearRs as $relationYear) {
    		if (!in_array($relationYear->year, $years) ) {
    			$relationYear->delete();
    		} else {
    			unset($years[array_search($relationYear->year, $years)]);
    		}
    	}
    	$relationYears = new Vakanz_Relation_Years();
    	foreach ($years as $year) {
    		$relationYear = $relationYears->createRow(
    			array(
    				'relation_id' => $relation->relation_id,
    				'year' => $year
    			)
   			);
    		$relationYear->save();
    	}
    }
    private function saveAttributes(Vakanz_Relation $relation) {
   
    	$selectedAttributes = $this->_getParam('attribute');
    	$relation_id = $relation->relation_id;
    	$relationAttributes = new Vakanz_Relation_Attributes();
    	$relationAttributesRs = $relation->findVakanz_Relation_Attributes();
    	foreach ($relationAttributesRs as $relationAttribute) {
    		if (!in_array($relationAttribute->attribute_id,$selectedAttributes) ) {
    			$relationAttribute->delete();
    		}
    		unset($selectedAttributes[array_search($relationAttribute->attribute_id,$selectedAttributes)]);
    	}
    	if (!empty($selectedAttributes)) {
	    	foreach ($selectedAttributes as $attribute_id) {
	    		$relationAttribute = $relationAttributes->createRow(
	    			array(
	    				'relation_id' => $relation_id,
	   					'attribute_id' => $attribute_id
	    			)
	    		);
	    		$relationAttribute->save();
	    	}
    	}

    }
}
